// src/middleware/prisma-date-formatter.ts
import { Prisma } from "@prisma/client";

/**
 * 格式化 Date 为 YYYY-MM-DD HH:mm:ss
 */
function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * 递归处理查询结果，将 Date 类型转换为字符串
 */
function processDatesInResult<T>(result: T): T {
  if (result instanceof Date) {
    return formatDate(result) as unknown as T;
  }

  if (Array.isArray(result)) {
    return result.map(processDatesInResult) as unknown as T;
  }

  if (result && typeof result === "object") {
    const obj = { ...result } as Record<string, any>;
    Object.keys(obj).forEach((key) => {
      if (obj[key] instanceof Date) {
        obj[key] = formatDate(obj[key]);
      } else if (obj[key] && typeof obj[key] === "object") {
        obj[key] = processDatesInResult(obj[key]);
      }
    });
    return obj as T;
  }

  return result;
}

/**
 * Prisma 中间件：自动格式化返回结果中的 Date 字段
 */
export function prismaDateFormatterMiddleware(): Prisma.Middleware {
  return async (params: Prisma.MiddlewareParams, next) => {
    // 执行查询
    const result = await next(params);

    // 只处理查询类操作
    if (
      params.action === "findUnique" ||
      params.action === "findMany" ||
      params.action === "findFirst" ||
      params.action === "aggregate" ||
      params.action === "groupBy"
    ) {
      return processDatesInResult(result);
    }

    return result;
  };
}
